package com.dangwen.proto.util;

import com.dangwen.proto.calculator.CmdHandler;

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

/**
 * Description
 *
 * @author DangWen
 */
public class ByteUtil {
    public static String bytesToHex(byte[] byteArray) {
        StringBuilder result = new StringBuilder();
        for (byte b : byteArray) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    public static byte[] objectToBytes(CmdHandler.ComToServerData obj) {
        // 将对象转换为字节数组
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {
            oos.writeObject(obj);
            // 现在 bytes 就包含了对象 obj 的字节表示
            return bos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

